// 不需验证token的路由
const tokenTime = 600;
const except_paths = [
	'/node/login',
	'/node/reg',
	'/node/log'
];

let db = require('../conn.js');
let r = require('../err.js');

async function checkToken(req, res, next){
	let token = req.query.token;
	if (!token) {
		res.json(r.error(5));
		return;
	}
	try{
		let tmp = await db.get('tokens').findOne({token});
		if (!tmp || !tmp.name) {
			res.json(r.error(5));
			return;
		}
	}catch(e){
		console.log(e);
		res.json(r.error(500,e));
		return;
	}
	var buf = new Buffer(token, 'base64');
	var info = buf.toString();
	info = info.split('@');
	var name = info[0];
	var time = info[1];
	var curTime = new Date().getTime();
	if (curTime > time && (curTime - time)/1000 < tokenTime) {
		next();
		return;
	}
	res.json(r.error(5));
}

module.exports = (req, res, next)=>{
	if (except_paths.some((o)=>req.path.startsWith(o))){
		next();
		return;
	}

	checkToken(req, res, next);
}
